package com.start.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.start.admin.entity.StartSysRoleMenu;
import com.start.admin.mappers.SysRoleMenuMapper;
import com.start.admin.service.StartSysRoleMenuService;
import com.start.common.exceptions.StartBusException;
import com.start.core.vo.RoleMenuVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StartSysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, StartSysRoleMenu> implements StartSysRoleMenuService {
    @Override
    public void save(RoleMenuVo roleMenuVo) {
        if (StringUtils.isEmpty(roleMenuVo.getRoleId())) throw new StartBusException("角色不能为空");
        LambdaQueryWrapper<StartSysRoleMenu> deleteQuery = new LambdaQueryWrapper<>();
        deleteQuery.eq(StartSysRoleMenu::getRoleId, roleMenuVo.getRoleId());
        remove(deleteQuery);
        getBaseMapper().deleteByRoleId(roleMenuVo.getRoleId());
        List<String> menuIds = roleMenuVo.getMenuIds().stream().filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
        if (menuIds.size() < 1) return;
        List<StartSysRoleMenu> startSysRoleMenus = new ArrayList<>();
        for (String menuId : menuIds) {
            startSysRoleMenus.add(new StartSysRoleMenu(roleMenuVo.getRoleId(), menuId));
        }
        saveBatch(startSysRoleMenus, 30);
    }
}
